﻿using BrnMall.Core.Domain.Rader;
using BrnMall.Manager.Domain.AddressBook;
using BrnMall.Manager.Domain.Rander;
using BrnMall.Manager.Manager.AddressBook;
using BrnMall.Manager.Manager.Radar;
using BrnMall.Manager.Manager.User;
using BrnMall.Services;
using BrnMall.Services.WJK;
using QIDong.WeApp.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WeiTap.Restful;
using static BrnMall.Manager.Domain.AddressBook.Clients;
using static BrnMall.Manager.Domain.User.User;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// 微街推-通讯录控制器
    /// </summary>
    public class AddressBookController : WebApi
    {

        #region  客户管理
        /// <summary>
        /// 我的客户列表
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="probability"></param>
        /// <param name="tags">标签</param>
        /// <param name="source">客户来源 (1 扫码, 2 转发)</param>
        /// <param name="search">客户昵称</param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public object ClientList(int staffId, int probability = 0, int tags = 0, int source = 0, string search = "", int PageNumber = 1, int PageSize = 10)
        {
            if (probability == 0 & tags == 0 & search == "" & source == 0)
                return AllClientList(staffId, PageNumber, PageSize);
            if (tags == 0 & search == "" & probability > 0)
                return GetCllientByProbability(probability, staffId, PageNumber, PageSize);
            if (staffId > 0 & tags > 0)
                return GetCllientByTags(staffId, tags, PageNumber, PageSize);
            if (source > 0)
                return GetClientBySource(staffId, source, PageNumber, PageSize);

            return ClientLists(staffId, PageNumber, PageSize);
        }

        /// <summary>
        /// 查询客户列表
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageNumber"></param>
        /// <returns></returns>
        public object ClientLists(int staffid, int PageSize, int PageNumber)
        {
            var bList = ClientManager.GetClientListPage(staffid, PageNumber, PageSize);
            if (bList.Items.Count < 1)
                return null;
            //foreach (var item in bList.Items)
            //{
            //    var user = BrnMall.Data.Users.GetUserById(item.Uid);
            //    if (user != null)
            //    {
            //        if (user.Avatar.Length > 0 && user.Avatar.IndexOf("http") != 0)
            //            item.Imgs = string.Format("http://static.711688.net.cn/upload/store/{0}/logo/source/{1}", item.Uid, user.Avatar);
            //        else
            //            item.Imgs = user.Avatar;
            //    }
            //}

            var model = new
            {
                List = bList.Items,
                PageModel = new PageModel(PageSize, PageNumber, (int)bList.TotalItems)
            };
            return model;
        }
        /// <summary>
        /// 查询所有的客户
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public ListModel<ClientView> AllClientList(int staffid, int PageNumber, int PageSize)
        {
            var dList = ClientManager.GetListPageAlll(staffid, PageNumber, PageSize);
            if (dList == null || dList.Items.Count < 1)
                return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in dList.Items)
                sb.AppendFormat(" {0},", item.Uid);

            var userList = UsersManager.GetByIds((sb.ToString()).Substring(1));

            foreach (var item in dList.Items)
            {
                var userInfo = UsersManager.FindUser(userList, item.Uid);
                BrnMall.Manager.Domain.User.User.UsersModel user = UsersManager.Get(item.Uid);
                if (user == null)
                {
                    continue;
                }
                var imgs = user.Avatar;
                item.Imgs = imgs;
                item.UserName = string.IsNullOrEmpty(item.UserName) ? userInfo.NickName : item.UserName;
                item.FollowUpCount = 0;

                var follow = ClientFollowManager.GetClientFollowByid(item.Id);
                if (follow != null)
                {
                    DateTime starttime = Convert.ToDateTime(follow.AddTime);
                    DateTime endtime = Convert.ToDateTime(DateTime.Now);
                    TimeSpan ts = starttime - endtime;
                    item.FollowUpCount = Math.Abs(ts.Days);
                }
            }
            var model = new ListModel<ClientView>();
            model.List = dList.Items;
            model.PageModel = new PageModel(PageSize, PageNumber, (int)dList.TotalItems);
            return model;
        }
        /// <summary>
        /// 根据预计成交概率查询客户
        /// </summary>
        /// <param name="probability"></param>
        /// <param name="staffid"></param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public ListModel<ClientView> GetCllientByProbability(int probability, int staffid, int PageNumber, int PageSize)
        {
            if (probability < 0)
                throw new Exception("预计成交概率");
            var dList = ClientManager.GetCllientByProbability(probability, staffid, PageNumber, PageSize);
            if (dList.Items.Count < 1)
                return null;

            StringBuilder sb = new StringBuilder();
            foreach (var item in dList.Items)
                sb.AppendFormat(" {0},", item.Uid);

            var userList = UsersManager.GetByIds((sb.ToString()).Substring(1));
            foreach (var item in dList.Items)
            {

                var userInfo = UsersManager.FindUser(userList, item.Uid);
                BrnMall.Manager.Domain.User.User.UsersModel user = UsersManager.Get(item.Uid);
                if (user == null)
                {
                    continue;
                }
                var imgs = user.Avatar;
                if (user.Avatar.Length > 0 && user.Avatar.IndexOf("http") != 0)
                {
                    imgs = string.Format("http://static.711688.net.cn/upload/store/{0}/logo/source/{1}", item.Uid, user.Avatar);
                }
                item.Imgs = imgs;
                item.UserName = userInfo.NickName;
                item.FollowUpCount = 0;
                var follow = ClientFollowManager.GetClientFollowByid(item.Id);
                if (follow != null)
                {
                    item.FollowUpCount = (int)Math.Round(DateTime.Now.Subtract(follow.AddTime).TotalDays);
                }
            }
            var model = new ListModel<ClientView>();
            model.List = dList.Items;
            model.PageModel = new PageModel(PageSize, PageNumber, (int)dList.TotalItems);
            return model;
        }

        /// <summary>
        /// 根据客户名称查询
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="search"></param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public object GetCllientBySearch(int staffid, string search, int PageNumber = 1, int PageSize = 15)
        {
            if (string.IsNullOrEmpty(search))
                throw new Exception("请输入搜索条件。");
            List<object> cvLists = new List<object>();
            var cvList = ClientManager.GetClientListPages(staffid, PageNumber, PageSize);
            foreach (var item in cvList.Items)
            {
                UsersModel um = UsersManager.Get(item.Uid);
                if (um == null) continue;
                if (um.NickName.IndexOf(search) == -1) continue;
                var cv = new
                {
                    ClientId=item.Id,
                    Staffid=item.Staffid,
                    Uid = um.Uid,
                    Avatar = um.Avatar,
                    NickName = um.NickName,
                    CreateTime = item.FollowTime.ToLongDateString()
                };
                cvLists.Add(cv);
            }
            return cvLists;
        }

        /// <summary>
        /// 根据标签查询
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="tags"></param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public ListModel<ClientView> GetCllientByTags(int staffid, int tags, int PageNumber, int PageSize)
        {
            if (tags < 0)
                throw new Exception("请选择标签。");
            var dList = ClientManager.GetCllientByTags(staffid, tags, PageNumber, PageSize);
            if (dList.Items.Count < 1)
                return null;

            StringBuilder sb = new StringBuilder();
            foreach (var item in dList.Items)
                sb.AppendFormat(" {0},", item.Uid);

            var userList = UsersManager.GetByIds((sb.ToString()).Substring(1));
            foreach (var item in dList.Items)
            {

                var userInfo = UsersManager.FindUser(userList, item.Uid);
                BrnMall.Manager.Domain.User.User.UsersModel user = UsersManager.Get(item.Uid);
                if (user == null)
                {
                    continue;
                }
                var imgs = user.Avatar;
                if (user.Avatar.Length > 0 && user.Avatar.IndexOf("http") != 0)
                {
                    imgs = string.Format("http://static.711688.net.cn/upload/store/{0}/logo/source/{1}", item.Uid, user.Avatar);
                }
                item.Imgs = imgs;
                item.UserName = userInfo.NickName;
                item.FollowUpCount = 0;
                var follow = ClientFollowManager.GetClientFollowByid(item.Id);
                if (follow != null)
                {
                    item.FollowUpCount = (int)Math.Round(DateTime.Now.Subtract(follow.AddTime).TotalDays);
                }
            }
            var model = new ListModel<ClientView>();
            model.List = dList.Items;
            model.PageModel = new PageModel(PageSize, PageNumber, (int)dList.TotalItems);
            return model;
        }

        /// <summary>
        /// 根据标签查询
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="tags"></param>
        /// <param name="PageNumber"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public ListModel<ClientView> GetClientBySource(int staffid, int source, int PageNumber, int PageSize)
        {
            if (source < 0)
                throw new Exception("请选择客户来源。");
            var dList = ClientManager.GetCllientBySource(staffid, source, PageNumber, PageSize);
            if (dList.Items.Count < 1)
                return null;

            StringBuilder sb = new StringBuilder();
            foreach (var item in dList.Items)
                sb.AppendFormat(" {0},", item.Uid);

            var userList = UsersManager.GetByIds((sb.ToString()).Substring(1));
            foreach (var item in dList.Items)
            {

                var userInfo = UsersManager.FindUser(userList, item.Uid);
                BrnMall.Manager.Domain.User.User.UsersModel user = UsersManager.Get(item.Uid);
                if (user == null)
                {
                    continue;
                }
                var imgs = user.Avatar;
                if (user.Avatar.Length > 0 && user.Avatar.IndexOf("http") != 0)
                {
                    imgs = string.Format("http://static.711688.net.cn/upload/store/{0}/logo/source/{1}", item.Uid, user.Avatar);
                }
                item.Imgs = imgs;
                item.UserName = userInfo.NickName;
                item.FollowUpCount = 0;
                var follow = ClientFollowManager.GetClientFollowByid(item.Id);
                if (follow != null)
                {
                    item.FollowUpCount = (int)Math.Round(DateTime.Now.Subtract(follow.AddTime).TotalDays);
                }
            }
            var model = new ListModel<ClientView>();
            model.List = dList.Items;
            model.PageModel = new PageModel(PageSize, PageNumber, (int)dList.TotalItems);
            return model;
        }

        /// <summary>
        /// 获取未添加的标签客户
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="tagId"></param>
        /// <param name="pageNumber"></param>
        /// <param name="PgeSize"></param>
        /// <returns></returns>
        public object GetClientListByTag(int staffId, int tagId, int pageNumber = 1, int PgeSize = 15)
        {
            var listClient = ClientManager.GetClientListNotIn(staffId, tagId, pageNumber, PgeSize);
            var list = new List<object>();
            foreach (var item in listClient.Items)
            {
                var user = Users.GetPartUserById(item.Uid);
                list.Add(new
                {
                    Id = item.Id,
                    Uid = item.Uid,
                    StaffId = item.staffId,
                    NickName=item.MemoName,
                    Avater = user != null ? user.Avatar : string.Empty
                });
            }

            var model = new
            {
                List = list,
                PageModel = new PageModel(PgeSize, pageNumber, (int)listClient.TotalItems)
            };
            return model;
        }

        /// <summary>
        /// 根据客户的id获取信息
        /// </summary>
        /// <param name="clientid"></param>
        /// <returns></returns>
        public ClientModel GetClient(int clientid)
        {
            if (clientid < 0)
                throw new Exception("请选择客户");

            var client = ClientManager.Get(clientid);
            if (client == null)
                throw new Exception("客户不存在");

            return GetClient(client);
        }

        public Clients GetClientInfo(int uid, int staffId)
        {
            if (uid < 1 || staffId < 1)
                throw new Exception("客户不存在");

            return ClientManager.GetByUid(uid, staffId);
        }

        //public ClientModel GetClientByUid(int uid, int staffId)
        //{
        //    if (uid < 0)
        //        throw new Exception("请选择客户");

        //    var client = ClientManager.GetByUid(uid, staffId);
        //    if (client == null)
        //        throw new Exception("客户不存在");

        //    return GetClient(client);
        //}

        private ClientModel GetClient(Clients client)
        {
            var user = Users.GetPartUserById(client.Uid);
            var model = new ClientModel()
            {
                Uid = client.Uid,
                Addtime = client.Addtime,
                Adress = client.Address,
                Birthday = client.Birthday,
                Avater = user.Avatar,
                tradeDate = client.tradeDate,
                Company = client.Company,
                Email = client.Email,
                Sex = client.Sex,
                Probability = client.Probability,
                Tags = client.Tags,
                MemoName = client.MemoName,
                Mobile = client.Mobile,
                Source = client.Source,
                Remark = client.Remark,
                Staffid = client.Staffid,
                FollowTime = client.FollowTime,
                FollowUpCount = 0,
                NoContactCount = 0
            };

            var follow = ClientFollowManager.GetFollowDays(client.Staffid, client.Id);
            //跟进天数
            if (follow != null)
            {
                if (follow.FirstAddTime > DateTime.MinValue)
                    model.NoContactCount = (int)Math.Round(DateTime.Now.Subtract(follow.LastAddtime).TotalDays);
                if (follow.FirstAddTime > DateTime.MinValue)
                {
                    var maxDays = DateTime.Now.Subtract(follow.LastAddtime).TotalDays;
                    if (maxDays > Math.Floor(maxDays))
                        model.FollowUpCount = (int)maxDays + 1;
                    else
                        model.FollowUpCount = (int)maxDays;
                }                    
            }
            return model;
        }

        /// <summary>
        /// 修改预计成交日期
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="updatetime"></param>
        /// <returns></returns>
        public int UpdateTradeDate(int clientId, string updatetime)
        {
            if (clientId < 0)
                throw new Exception("客户的id为空");
            if (string.IsNullOrEmpty(updatetime))
                throw new Exception("预计成交时间不能为空");
            return ClientManager.UpdateTradeDate(clientId, updatetime);
        }
        /// <summary>
        /// 修改预计成交概率
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="probability"></param>
        /// <returns></returns>
        public int UpdateProbability(int clientId, int probability)
        {
            if (clientId < 0)
                throw new Exception("客户的id为空");
            if (probability < 0)
                throw new Exception("预计成交概率不能为空");
            return ClientManager.UpdateProbability(clientId, probability);
        }
        /// <summary>
        /// 修改会员标签名
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public bool UpdateTags(int clientId, int tags)
        {
            if (clientId < 0)
                throw new Exception("客户的id为空");
            if (tags < 0)
                throw new Exception("会员标签名不能为空");
            return ClientManager.UpdateTags(clientId, tags);
        }

        /// <summary>
        /// 修改客户资料
        /// </summary>
        public bool UpdateClient(int clientId, string MemoName, string Mobile, string Email, string Company, string Birthday, string Address, int Sex)
        {
            var client = ClientManager.Get(clientId);
            client.MemoName = MemoName;
            client.Address = Address;
            client.Sex = Sex;
            client.Mobile = Mobile;
            client.Email = Email;
            client.Company = Company;
            client.Birthday = string.IsNullOrEmpty(Birthday) ? DateTime.MinValue : Convert.ToDateTime(Birthday);

            return ClientManager.Update(client);
        }
        #endregion

        #region 客户标签

        /// <summary>
        /// 添加客户标签
        /// </summary>
        /// <returns></returns>
        public int AddClientTag(int staffId, int categoryId=100, string tagName="")
        {
            if (tagName == "")
                throw new Exception("请输入标签名称！");
            if (ClientTagManager.Exists(staffId, tagName))
                throw new Exception("标签名重复");

            return ClientTagManager.Add(new ClientTag() { StaffId = staffId, TagName = tagName, CategoryId = categoryId });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateClientTag(ClientTag model) {
            if (ClientTagManager.Exists(model.StaffId, model.TagName))
                throw new Exception("标签名重复");
            return ClientTagManager.Update(model);
        }

        /// <summary>
        /// 标签页面
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<ClientTag> ClientTagList(int staffId, int page = 1, int pageSize = 100)
        {
            return ClientTagManager.GetList(staffId, page, pageSize);
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int DeleteClientTag(int Id)
        {
            return ClientTagManager.Delete(Id);
        }

        #endregion

        #region 客户与标签的关联

        /// <summary>
        /// 客户与标签的关联列表
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<ClientTagRelModel> GetTagRelationList(int staffId, int page = 1, int pageSize = 100)
        {
            //List<ClientTagRelModel> list = new List<ClientTagRelModel>();
            //foreach (ClientTag ct in ClientTagManager.GetList(staffId, page,pageSize))
            //{
            //    list.Add(new ClientTagRelModel
            //    {
            //        ctList = ct,
            //        crList = ClientRelationsManager.GetList(ct.Id, page, pageSize)
            //    });
            //}

          
            var relationsList = ClientRelationsManager.GetList(staffId);
            var tagList = ClientTagManager.GetList(staffId, page, pageSize);

            var list = new List<ClientTagRelModel>();

            foreach (var tag in tagList)
            {
                var relations = relationsList.FindAll(x => x.ClientTagid == tag.Id);
                if (relations.Count== 0)
                    continue;
                list.Add(new ClientTagRelModel
                {
                    Tag = tag,
                    relations = relations
                });
            }
            return list;
        }

        /// <summary>
        /// 获取单个用户的标签信息
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="clientId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public object GetTagRelationListById(int Id = 0, int staffId = 0, int clientId = 0, int page = 1, int pageSize = 10)
        {
            var model = ClientTagManager.GetClientTag(staffId, clientId);
            var clientmodel = ClientManager.Get(clientId);
            var obj = new
            {
                csList = model,
                clientmodel,
                ctList = ClientTagManager.GetClientTagById(Id),
                crList = ClientRelationsManager.GetList(Id, page, pageSize),

            };
            return obj;
        }
        /// <summary>
        /// 更新该客户的标签
        /// </summary>
        /// <returns></returns>
        public bool AddTagRelation(int clientTagid, int clientid, string tagname)
        {
            var ctList = ClientTagManager.GetClientTagById(clientTagid);
            //判断该条记录是否存在
            var update = ClientManager.UpdateTagName(tagname, clientid);
            var RelationModel = ClientRelationsManager.GetClientRelations(clientTagid);
            if (RelationModel != null)
            {
                var res = ClientRelationsManager.Delete(RelationModel.Id);
                if (res > 0)
                    return true;
                else
                    return false;
            }
            //获取对应的标签信息
            var clientmodel = ClientManager.Get(clientid);
            //
            var user = BrnMall.Data.Users.GetUserById(clientmodel.Uid);
            //获取上级信息
            var staffmodel = StaffManager.Get(clientmodel.Staffid);
            var model = new ClientRelations
            {
                ClientTagid = ctList.Id,
                Addtime = DateTime.Now,
                Avatar = staffmodel.Avater,
                Clientid = clientid,
                NickName = user.NickName,
                StaffId = staffmodel.Id
            };
            if (update > 0)
                return ClientRelationsManager.Insert(model);
            else
                return ClientRelationsManager.Insert(model);
        }

        /// <summary>
        /// 标签客户关系
        /// </summary>
        /// <param name="ClientTagId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<ClientRelations> ClientRelationsList(int ClientTagId, int page = 1, int pageSize = 10)
        {
            return ClientRelationsManager.GetList(ClientTagId, page, pageSize);
        }

        /// <summary>
        /// 删除关系
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int DeleteClientRelations(int Id)
        {
            return ClientRelationsManager.Delete(Id);
        }

        /// <summary>
        /// 添加标签客户
        /// </summary>
        /// <param name="StaffId"></param>
        /// <param name="clientIds"></param>
        /// <param name="ClientTagId"></param>
        /// <returns></returns>
        public int AddClientTagRelations(int StaffId, string clientIds, int ClientTagId)
        {
            var count = 0;
            var arrClientId = clientIds.Split(',');
            foreach (var cid in arrClientId)
            {
                if (string.IsNullOrEmpty(cid))
                    continue;
                var clientId = Convert.ToInt32(cid);
                if (ClientRelationsManager.IsExists(StaffId, clientId, ClientTagId) > 0)
                    continue;

                var client = ClientManager.Get(clientId);
                if (client == null) continue;

                var user = UsersManager.Get(client.Uid);
                if (user == null) continue;

                count += ClientRelationsManager.Add(new ClientRelations
                {
                    StaffId = StaffId,
                    Clientid = clientId,
                    ClientTagid = ClientTagId,
                    NickName = client != null ? client.MemoName : user.NickName.Trim(),
                    Avatar = user.Avatar.Trim(),
                    Addtime = DateTime.Now
                });
            }

            return count;
        }

        #endregion

        #region 客户跟进

        #endregion

        #region 客户AI分析
        /// <summary>
        /// 客户的AI数据
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public object GetAnalysis(int clientId, int staffId)
        {
            var client = ClientManager.Get(clientId);
            if (client == null) return null;

            //近15日客户活跃度
            var dateRecord = ActionRecordManager.GetGroupbyDate(client.Uid, staffId, DateTime.Now.AddDays(-15).ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMdd"));

            //客户与我的互动
            var actionRecord = ActionRecordManager.GetGroupbyActionType(client.Uid, staffId);
            var model = new
            {
                ActionRecord = actionRecord,
                DateRecord = dateRecord
            };
            return model;
        }

        /// <summary>
        /// 我的报表 - 其他报表
        /// </summary>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public object GetMyReport(int staffId, int days = -15)
        {

            //近15日客户活跃度
            var dateRecord = ActionRecordManager.GetGroupbyDate(staffId, DateTime.Now.AddDays(days).ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMdd"));
            //客户与我的互动
            var actionRecord = ActionRecordManager.GetGroupbyActionType(staffId);

            var model = new
            {
                ActionRecord = actionRecord,
                DateRecord = dateRecord
            };
            return model;
        }
        #endregion

        #region boss统计数据

        /// <summary>
        /// 汇总统计
        /// </summary>
        /// <returns></returns>
        public object GetTotalByDate(int staffId, int DepartmentId = 0, int days = 0)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

            //我的部门员工
            var staffList = StaffDepartmentManager.GetChildList(staffId, DepartmentId);
            var staffIds = Staffs.GetStaffIds(staffList);

            //客户总数
            var clientCount = ClientManager.GetTotalClient(staffIds, startTime, endTime);

            //操作统计
            var actionTotal = ActionRecordManager.GetActionTotal(staffIds, startTime, endTime);
            var model = new
            {
                ClientCount = clientCount,
                ActionTotalList = actionTotal
            };
            return model;
        }

        /// <summary>
        /// boss - 成交率统计
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <param name="DepartmentId">部门ID(0 表示所有部门)</param>
        /// <param name="days">查询的天数(7天内，15天内，30天内)</param>
        /// <returns></returns>
        public object GetTotalProbability(int staffId, int DepartmentId = 0, int days = 7, int isBoss = 0)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");
            var staffIds = staffId.ToString();

            //ai销售看自己的客户数据，boss看我所属的部门数据
            if (isBoss == 1)
            {
                var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
                staffIds = Staffs.GetStaffIds(deptList);
            }

            //客户成交率
            var probabilityList = ClientManager.GetProbabilityList(staffIds, startTime, endTime);

            var scoreList = new List<int>() { 0, 0, 0, 0 };
            probabilityList.ForEach((x) =>
            {
                if (x.Probability <= 50) scoreList[0]++;
                else if (x.Probability > 50 && x.Probability <= 80) scoreList[1]++;
                else if (x.Probability > 80 && x.Probability <= 99) scoreList[2]++;
                else if (x.Probability > 99) scoreList[3]++;
            });

            var model = new
            {
                total_count = probabilityList.Count,
                column = new List<string>() { "<=50%", "<=80%", "<=99%", ">99%" },
                value = scoreList
            };
            return model;
        }

        /// <summary>
        /// boss - 客户数统计
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <param name="DepartmentId">部门ID(0 表示所有部门)</param>
        /// <param name="days">查询的天数(7天内，15天内，30天内)</param>
        /// <returns></returns>
        public object GetClientByDate(int staffId, int DepartmentId = 0, int days = 7)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");

            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var deptIds = Staffs.GetMyDepartmentIds(deptList, DepartmentId);

            //新增客户数(7天,15天,30天)
            var dayList = ClientManager.GetClientByDate(deptIds, startTime, endTime);

            var model = new
            {
                days = days,
                value = dayList
            };
            return model;
        }

        /// <summary>
        /// boss - 跟进数统计
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <param name="DepartmentId">部门ID(0 表示所有部门)</param>
        /// <param name="days">查询的天数(7天内，15天内，30天内)</param>
        /// <returns></returns>
        public object GetFollowByDate(int staffId, int DepartmentId = 0, int days = 7)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");

            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var staffIds = Staffs.GetStaffIds(deptList);

            var model = new
            {
                days = days,
                value = ClientManager.GetFollowByDate(staffIds, startTime, endTime)
            };
            return model;
        }

        /// <summary>
        /// boss - 咨询数
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <param name="DepartmentId">部门ID(0 表示所有部门)</param>
        /// <param name="days">查询的天数(7天内，15天内，30天内)</param>
        /// <returns></returns>
        public object GetImByDate(int staffId, int DepartmentId = 0, int days = 7)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");

            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var staffIds = Staffs.GetStaffIds(deptList);
            var dayTotal = ActionRecordManager.GetDayTotal(staffIds, startTime, endTime);
            foreach (var item in dayTotal)
            {
                item.Date = string.Format("{0}-{1}-{2} 00:00:00", item.Date.Substring(0, 4), item.Date.Substring(4, 2), item.Date.Substring(6, 2));
            }
            var model = new
            {
                days = days,
                value = dayTotal
            };
            return model;
        }
        
        /// <summary>
        /// boss - 客户与我互动
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <param name="DepartmentId">部门ID(0 表示所有部门)</param>
        /// <param name="days">查询的天数(7天内，15天内，30天内)</param>
        /// <returns></returns>
        public object GetActionByDate(int staffId, int DepartmentId = 0, int days = 7)
        {
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");

            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var staffIds = Staffs.GetStaffIds(deptList);
            var dayTotal = ActionRecordManager.GetActionTotal(staffIds, startTime, endTime);
            var model = new
            {
                days = days,
                value = dayTotal
            };
            return model;
        }

        /// <summary>
        /// 销售排行
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="DepartmentId"></param>
        /// <param name="group">数据分组(1 客户数-总人数倒序,2 客户数-新客户倒序 ,3 跟进数-总数倒序,4 跟进数-咨询数倒序, 5 成交率倒序)</param>
        /// <param name="orderBy"></param>
        /// <param name="days"></param>
        /// <returns></returns>
        public object GetSalesList(int staffId, int DepartmentId = 0, int group = 1, int days = 0, int minNum = 0, int maxNum = 0)
        {
            if (group < 1)
                throw new Exception("请选择客户人数、互动评率、成交率的一种");
            var startTime = days > 0 ? DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd") : string.Empty;
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");

            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var deptIds = Staffs.GetMyDepartmentIds(deptList, DepartmentId);

            //客户数倒序
            if (group == 1 || group == 2)
            {
                return ClientManager.GetSalesListByClient(deptIds, startTime, endTime);
            }
            //跟进数倒序
            if (group == 3)
            {
                return ClientManager.GetSalesListByFollow(deptIds, startTime, endTime);
            }
            //互动评率倒序
            if (group == 4)
            {
                return ClientManager.GetSalesListByIM(deptIds, startTime, endTime);
            }
            //成交率倒序
            if (group == 5)
            {
                return ClientManager.GetSalesListByProbability(deptIds, minNum, maxNum);
            }
            return null;
        }

        /// <summary>
        /// boos - 员工AI分析
        /// </summary>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public object GetAnalysisByStaff(int staffId)
        {
            //我的所有部门ID
            var deptList = StaffDepartmentManager.GetMyDeportment(staffId);
            var staffIds = Staffs.GetStaffIds(deptList);

            //查看名片, 客户互动值,  查看官网, 查看商品, 获客能力 等操作
            var actionTypes = string.Format("{0},{1},{2}",
                (int)ActionRecordState.ShowCard,
                (int)ActionRecordState.ShowNetwork,
                (int)ActionRecordState.ShowProduct,
                (int)ActionRecordState.OpenImDialog);

            var actionTotalList = ActionRecordManager.GetTotalGroupByStaffId(staffIds, actionTypes);

            var staffList = StaffManager.GetListByIds(staffIds);
            var staff = new List<object>();

            string[] staffIdList = staffIds.Split(',');
            var oldId = new List<string>();

            foreach (var id in staffIdList)
            {
                if (string.IsNullOrEmpty(id)) continue;
                if (oldId.Contains(id)) continue;
                oldId.Add(id);

                var _staffid = Convert.ToInt32(id);
                //获客能力，单独查询 
                var clientCount = ClientManager.GetTotalClient(staffIds, string.Empty, string.Empty);
                var item = new RadarNumInfo()
                {
                    actionType = (int)ActionRecordState.AddClient,
                    Total = clientCount,
                    StaffId = Convert.ToInt32(id)
                };

                //跟进数，单独查询 
                var followCount = ClientFollowManager.GetFollowTotal(_staffid);
                var itemFollow = new RadarNumInfo()
                {
                    actionType = (int)ActionRecordState.FollowClient,
                    Total = followCount,
                    StaffId = Convert.ToInt32(id)
                };
                actionTotalList.Add(item);
                actionTotalList.Add(itemFollow);

                //成员信息
                var tempStaff = staffList.Find(x => x.Id == _staffid);
                staff.Add(new { staffid = tempStaff.Id, name = tempStaff.Name, position = tempStaff.Position, avater = tempStaff.Avater });
            }

            var model = new
            {
                ActionRecordList = actionTotalList,
                StaffList = staff
            };
            return model;
        }


        #endregion

        #region 跟进语
        /// <summary>
        /// 添加跟进语
        /// </summary>
        /// <param name="staffId"></param>
        /// <param name="clientId"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public bool AddClientFollow(int staffId = 0, int clientId = 0, string content = "")
        {
            if (staffId < 0)
                throw new Exception("业务员id不能为空！");
            if (clientId < 0)
                throw new Exception("请选择客户");
            if (content == "")
                throw new Exception("跟进语不能为空");
            var model = new ClientFollow() { StaffId = staffId, ClientId = clientId, Content = content, AddTime = DateTime.Now };

            bool isAdd = ClientFollowManager.Add(model);
            if (isAdd)
                ClientManager.UpdateFollowTime(clientId);
            return isAdd;
        }
        /// <summary>
        /// 跟进语列表
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="clientid"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public object GetClientFollowListPages(int staffid, int clientid, int page = 1, int pageSize = 10)
        {
            var dList = ClientFollowManager.GetClientFollowListPages(staffid, clientid, page, pageSize);
            var list = new List<ClientFollowModel>();
            foreach (var item in dList.Items)
            {
                var info = new ClientFollowModel
                {
                    ClientId = clientid,
                    StaffId = staffid,
                    AddTime = item.AddTime.ToString("yyyy-MM-dd"),
                    Content = item.Content
                };
                list.Add(info);
            }
            var model = new
            {
                PageModel = new PageModel(pageSize, page, (int)dList.TotalItems),
                FollowList = list
            };
            return model;
        }
        #endregion
    }
}